< previous page page_71 next page >

Page 71
note.gif Although this example uses code to add items, you can also create the list at designtime by typing the text that you want to appear in the List property of a list box. Each line in the property corresponds to a selection that is presented to the users. After you add an item to the list, press Ctrl+Enter to move to the next line of the list. square.gif

Run the project, and you'll notice that 100 lines of text appear in the list box. To clear all the items in a list box, use the Clear method, as in the following example:
List1.Clear
The items in a list box are stored in an array, which is accessible via the List property of the list box. The list array starts with a zero index, so to print the first item in the list, you can use the following statement:
Print List1.List(0)
You can test this statement by putting the sample program in break mode (press Ctrl+Break) and entering the Print statement in the Immediate window.
Two other properties are critical for using a list box: ListCount and ListIndex. ListCount represents the number of items in a list box. ListIndex represents the selected item.
CAUTION
When you are using ListCount in a loop to examine the contents of an unknown number of items, remember that the List array starts with zero, so your code should look like this:
For i = 0 To List1.ListCount - 1
'Process List1.List(i)
Next i

note.gifListindex is 1 if no item is selected. square.gif

To illustrate the ListIndex property in action, stop the sample program and add the following code to the Click event of the list box:
Msgbox List1.List(List1.ListIndex)
Run the program again, and when you click an item, it is displayed in a message box.
Another way to retrieve the value of the list box item selected by the user is to check the list box's Text property. The Text property contains the item from whichever line of the list box has the focus. If it's a simple list box, the line that the user clicked is returned in the Text property. If no list box item has yet been clicked, the Text property contains an empty string ("").
To remove items from the list box, use the RemoveItem method, specifying the array index of the item you want removed from the list. To demonstrate, add the following line of code to the KeyDown event of the list box:

 
< previous page page_71 next page >